package cn.edu.swufe.surverpark.struts2.service.impl;

import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.edu.swufe.surverpark.model.Role;
import cn.edu.swufe.surverpark.model.User;
import cn.edu.swufe.surverpark.struts2.dao.BaseDao;
import cn.edu.swufe.surverpark.struts2.service.RoleService;
import cn.edu.swufe.surverpark.struts2.service.UserService;
import cn.edu.swufe.surverpark.util.ValidateUtil;

/**
 *@author 陈龙 E-mail:529914446@qq.com
 *@version创建时间:2015年4月29日下午6:08:57
 *类说明
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> 
							 implements UserService {
	
	@Resource(name="roleService")
	private RoleService roleService;
	@Resource(name="userDao")
	public void setDao(BaseDao<User> dao) {
		// TODO Auto-generated method stub
		super.setDao(dao);
	}

	@Override
	public boolean isRegisted(String email) {
		String hql = "FROM User u WHERE u.email = ?";
		List<User> list = this.findEntityByHQL(hql, email);
		return ValidateUtil.isValid(list);
	}

	public User validateLoginInfo(String email, String md5) {
		String hql = "FROM User u WHERE u.email = ? AND u.password = ?";
		User user = (User) this.uniqueResult(hql, email,md5);
		if(user != null){
			user.getRoles().size();
			return user;
		}
		return null;
	}

	@Override
	public User getEntityWithRoles(Integer userId) {
		User user = getEntity(userId);
		user.getRoles().size();
		return user;
	}

	@Override
	public void saveOrUpdateRole(User model, Integer[] ids) {
		model = getEntity(model.getId());
		if(!ValidateUtil.isValid(ids)){
			model.getRoles().clear();
		}else{
			List<Role> roles = roleService.findRolesInRange(ids);
			model.setRoles(new HashSet<Role>(roles));
		}
	}

	@Override
	public void clearAuthorize(Integer userId) {
		User u = getEntity(userId);
		u.getRoles().clear();
	}
}

